package com.fly.simple;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.SystemUtils;

import com.fly.simple.utils.FreeMarkerUtil;
import com.fly.simple.utils.ShellExecutor;

import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TemplateRun
{
    /**
     * Args4j是一个开源的Java库，由Kohsuke Kawaguchi开发。它通过注解的方式，使得命令行参数的解析变得异常简单
     * 
     * @param args
     * @throws IOException
     * @throws TemplateException
     * @throws InterruptedException
     */
    public static void main(String[] args)
        throws IOException, TemplateException, InterruptedException
    {
        // 写入文件
        if (SystemUtils.IS_OS_WINDOWS)
        {
            File file = new File("index.html");
            creatPage("index.html");
            
            // 打开页面10秒后删除文件
            Runtime.getRuntime().exec("cmd /c start /min " + file.getCanonicalPath());
            TimeUnit.SECONDS.sleep(10);
            file.deleteOnExit();
            return;
        }
        if (SystemUtils.IS_OS_LINUX)
        {
            log.info("will update docker info");
            // crontab -e
            // */30 * * * * java -jar /work/gitcode/docker-run/docker-show-jar-with-dependencies.jar
            creatPage("/usr/share/nginx/html/index.html");
        }
    }
    
    /**
     * 更新docker应用页面
     * 
     * @param file
     * @throws IOException
     * @throws TemplateException
     * @see [类、类#方法、类#成员]
     */
    private static void creatPage(String file)
        throws IOException, TemplateException
    {
        // 收集docker信息
        Map<String, Object> model = new HashMap<>(3);
        model.put("date", new Date());
        model.put("map", ShellExecutor.getDockerInfo());
        
        // {mysql5=[3306, 13306], mysql8=[23306], redis-server=[6379]}
        String content = FreeMarkerUtil.renderTemplate("/templates/index.html.ftl", model);
        try (FileWriter writer = new FileWriter(file))
        {
            writer.write(content);
            writer.flush();
        }
    }
}
